<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="患者编号" prop="patientId">
        <el-input
          v-model="queryParams.patientId"
          placeholder="请输入患者编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="患者来源" prop="subId">
        <el-cascader
          style="width: 230px"
          :props="defaultProps"
          @change="handleSubChange"
          clearable
          :options="deptOptions"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="建议标题" prop="drugName">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入建议标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="建议状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择用药建议状态"
          clearable
        >
          <el-option
            v-for="dict in dict.type.gonitis_medication_advice"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 230px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['gonitis:medication:advice:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['gonitis:medication:advice:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['gonitis:medication:advice:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['gonitis:medication:advice:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="medAdviceList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" v-if="true" />
      <el-table-column
        label="患者编号"
        align="center"
        prop="patientId"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="患者姓名" align="center" prop="patientName">
        <template slot-scope="scope">
          <span>{{ scope.row.patientName ? scope.row.patientName : "暂无" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="医生编号" align="center" prop="doctorId" />
      <el-table-column label="医生姓名" align="center" prop="doctorName" />
      <el-table-column label="患者来源" align="center" prop="subName" />
      <el-table-column
        label="建议标题"
        align="center"
        prop="title"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="每日次数" align="center" prop="medFrequency" />
      <el-table-column label="创建时间" width="100" align="center" prop="createTime" />
      <el-table-column label="建议状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.gonitis_medication_advice"
            :value="scope.row.status"
          />
        </template>
      </el-table-column>
      <el-table-column
        width="150"
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['gonitis:medication:advice:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['gonitis:medication:advice:remove']"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            v-hasPermi="['gonitis:medication:advice:detail']"
            @click="handleDetail(scope.row)"
            >详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改medAdvice对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="40%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="选择患者" prop="patientId" v-if="!form.id">
          <el-cascader
            style="width: 230px"
            :props="defaultProps"
            v-model="formSub"
            @change="formSubChange"
            :options="subOptions"
          ></el-cascader>
          <el-select style="width: 230px" v-model="form.patientId" placeholder="请选择">
            <el-option
              v-for="item in patientOptions"
              :key="item.id"
              :label="'[姓名] ' + item.name + '  [电话] ' + item.phone"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="建议标题" prop="title">
          <el-input
            :maxlength="18"
            show-word-limit
            clearable
            v-model="form.title"
            placeholder="请输入建议标题"
          />
        </el-form-item>
        <el-form-item label="药品名称" prop="drugName">
          <el-select
            @change="drugNameChange"
            v-model="drugNames"
            multiple
            filterable
            allow-create
            placeholder="请选择药品名称"
          >
            <el-option
              v-for="(item, index) in drugNameList"
              :key="index"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="每日次数" prop="medFrequency">
          <el-input-number
            v-model="form.medFrequency"
            :min="1"
            :max="10"
            label="填写用药次数"
          />
        </el-form-item>
        <el-form-item label="用药说明" prop="medComment">
          <el-input
            type="textarea"
            :maxlength="100"
            :autosize="{ minRows: 2, maxRows: 4 }"
            show-word-limit
            clearable
            v-model="form.medComment"
            placeholder="请输入用药说明"
          />
        </el-form-item>
        <el-form-item label="服用时间" prop="medTime">
          <el-time-select
            v-model="medTime"
            @change="medTimeChange"
            :picker-options="{ start: '06:00', step: '00:15', end: '23:00' }"
            placeholder="选择时间"
          ></el-time-select>
          <div>
            <el-tag
              style="margin-left: 5px"
              v-for="(item, index) in timeTags"
              :disable-transitions="false"
              @close="handleTagClose(item)"
              :key="index"
              closable
              >{{ item }}</el-tag
            >
          </div>
        </el-form-item>
        <el-form-item label="建议状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择">
            <el-option
              v-for="dict in dict.type.gonitis_medication_advice"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value + ''"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用药备注" prop="remark">
          <el-input
            clearable
            type="textarea"
            v-model="form.remark"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm"
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :before-close="handleClose"
      :title="detailTitle"
      :visible.sync="detailOpen"
      width="40%"
      append-to-body
    >
      <div v-loading="detailLoading">
        <el-descriptions class="margin-top" :column="2" direction="vertical" border>
          <el-descriptions-item>
            <template slot="label">编号</template>
            {{ adviceInfo.id }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">患者来源</template>
            {{ adviceInfo.subName }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">患者编号</template>
            {{ adviceInfo.patientId }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">患者姓名</template>
            {{ adviceInfo.patientName }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">医生编号</template>
            {{ adviceInfo.doctorId }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">医生姓名</template>
            {{ adviceInfo.doctorName }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">建议标题</template>
            {{ adviceInfo.title }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">药品集合</template>
            <el-tag
              style="margin-right: 5px"
              v-for="(item, index) in adviceInfo.drugList"
              :key="index"
              size="small"
              >{{ item }}</el-tag
            >
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">用药时间</template>
            <el-tag
              style="margin-right: 5px"
              v-for="(item, index) in adviceInfo.timeList"
              :key="index"
              size="small"
              >{{ item }}</el-tag
            >
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">创建时间</template>
            {{ adviceInfo.createTime }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">建议备注</template>
            {{ adviceInfo.remark ? adviceInfo.remark : "暂无" }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listMedAdvice,
  getMedAdvice,
  delMedAdvice,
  addMedAdvice,
  updateMedAdvice,
  medAdviceDetail,
} from "@/api/gonitis/medAdvice";
import { subTree } from "@/api/gonitis/illSub";
import { listBySubId } from "@/api/gonitis/patient";
export default {
  name: "MedAdvice",
  dicts: ["gonitis_medication_advice"],
  data() {
    return {
      dateRange: [],
      formSub: undefined,
      adviceInfo: {},
      detailLoading: false,
      detailOpen: false,
      detailTitle: "",
      drugNameList: ["布洛芬缓释片", "阿司匹林片", "消炎痛", "硫酸氨基葡萄糖"], // 药品集合
      // 药物名称集合
      drugNames: [],
      subOptions: [],
      // 病情列表
      deptOptions: [],
      // 病情多选框映射
      defaultProps: {
        children: "children",
        label: "label",
        value: "id",
      },
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // medAdvice表格数据
      medAdviceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        patientId: undefined,
        subId: undefined,
        drugName: undefined,
        status: undefined,
      },
      timeTags: [],
      // 用药时间
      medTime: "",
      // 患者集合
      patientOptions: [],
      // 表单参数
      form: {
        drugName: "",
        medFrequency: 1,
      },
      // 表单校验
      rules: {
        patientId: [{ required: true, message: "患者编号不能为空", trigger: "change" }],
        title: [{ required: true, message: "建议标题不能为空", trigger: "blur" }],
        drugName: [
          { required: true, message: "药品名称集合不能为空", trigger: "change" },
        ],
        medFrequency: [
          { required: true, message: "每日次数不能为空", trigger: "change" },
        ],
        medComment: [{ required: true, message: "用药说明不能为空", trigger: "blur" }],
        medTime: [{ required: true, message: "服用时间不能为空", trigger: "blur" }],
        status: [
          {
            required: true,
            message: "建议状态不能为空",
            trigger: "change",
          },
        ],
      },
    };
  },
  created() {
    this.init();
  },
  methods: {
    /** 关闭对话框 */
    handleClose() {
      this.adviceInfo = {};
      this.detailOpen = false;
    },
    /** 药品改变 */
    drugNameChange(value) {
      this.form.drugName = "";
      this.form.drugName = value[0];
      for (let i = 1; i < value.length; i++) {
        this.form.drugName += "," + value[i];
      }
    },
    /** 点击时间 */
    medTimeChange(value) {
      this.form.medTime = "";
      const index = this.timeTags.indexOf(value);
      // 如果不存在相同值才添加
      if (index == -1 && value) {
        this.timeTags.push(value);
        this.form.medTime = this.timeTags[0];
        for (let i = 1; i < this.timeTags.length; i++) {
          this.form.medTime += "," + this.timeTags[i];
        }
      }
    },
    /** 底部标签变化 */
    handleTagClose(value) {
      this.form.medTime = "";
      const indexToRemove = this.timeTags.indexOf(value);
      // 如果存在就删除
      if (indexToRemove !== -1) {
        this.timeTags.splice(indexToRemove, 1);
        if (!this.timeTages || this.timeTages.length <= 0) {
          this.form.medTime = null;
        } else {
          this.form.medTime = this.timeTags[0];
          for (let i = 1; i < this.timeTags.length; i++) {
            this.form.medTime += "," + this.timeTags[i];
          }
        }
      }
    },
    /** 初始化 */
    init() {
      this.getDeptTree();
      this.getList();
    },
    /** 病情分类选择框改变 */
    formSubChange(value) {
      this.form.subId = value[value.length - 1];
      // 发送请求查询对应病情的病人
      listBySubId(this.form.subId).then((response) => {
        this.patientOptions = response.data;
      });
    },
    /** 病情分类选择框改变 */
    handleSubChange(value) {
      this.queryParams.subId = value[value.length - 1];
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      subTree().then((response) => {
        this.deptOptions = response.data;
        this.subOptions = response.data;
      });
    },
    /** 查询medAdvice列表 */
    getList() {
      this.loading = true;
      listMedAdvice(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          this.medAdviceList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        patientId: undefined,
        doctorId: undefined,
        subId: undefined,
        drugName: undefined,
        medFrequency: undefined,
        medComment: undefined,
        medTime: undefined,
        status: undefined,
        remark: undefined,
      };
      this.formSub = [];
      this.patientOptions = [];
      this.medTime = "";
      this.drugNames = "";
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.loading = false;
      this.open = true;
      this.title = "添加用药建议";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids;
      getMedAdvice(id).then((response) => {
        this.loading = false;
        this.form = response.data;
        this.form.status = response.data.status + "";
        this.drugNames = response.data.drugName.split(",");
        this.timeTags = response.data.medTime.split(",");
        this.open = true;
        this.title = "修改用药建议";
      });
    },
    /** 获取详情信息 */
    handleDetail(row) {
      this.detailTitle = "用药建议详情";
      this.detailOpen = true;
      this.detailLoading = true;
      const id = row.id;
      medAdviceDetail(id).then((response) => {
        this.adviceInfo = response.data;
        this.adviceInfo.drugList = response.data.drugName.split(",");
        this.adviceInfo.timeList = response.data.medTime.split(",");
        this.detailLoading = false;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateMedAdvice(this.form)
              .then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          } else {
            addMedAdvice(this.form)
              .then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除用药建议编号为"' + ids + '"的数据项？')
        .then(() => {
          this.loading = true;
          return delMedAdvice(ids);
        })
        .then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {})
        .finally(() => {
          this.loading = false;
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "gonitis/medAdvice/export",
        {
          ...this.queryParams,
        },
        `medAdvice_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
